<script setup lang="tsx">
import { reactive, ref, unref, markRaw, shallowRef, provide, type Component } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import Details from './component/Details.vue'
import { ElCollapseTransition, ElDialog } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { getListApi, delUserApi, detailsApi, type Row } from '@/api/logistics/waybill'
import tableData from './component/tableData.vue'
import { searchOrderApi } from '@/api/utils/search'
import { useSearch } from '@/hooks/web/useSearch'

defineOptions({
  name: 'Waybill'
})
const comId = reactive({
  Details: markRaw(Details)
})
const { searchRegister, searchMethods } = useSearch()
const { setSchema } = searchMethods
const searchUser = async (query) => {
  if (query && Object.values(query).every((item) => item !== '')) {
    setSchema([
      {
        field: 'id',
        path: 'componentProps.loading',
        value: true
      }
    ])
    const params = {
      ...query,
      field: 'deliver_task_id,no'
    }
    const res = await searchOrderApi(params)
    if (res) {
      setSchema([
        {
          field: 'id',
          path: 'componentProps.options',
          value: res.data.list.map((item) => {
            return {
              label: item.no,
              value: item.deliver_task_id
            }
          })
        }
      ])
    }
    setSchema([
      {
        field: 'id',
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: 'selection' }
  },
  {
    field: 'no',
    label: '运单编号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'id',
    label: '关联订单号',
    search: {
      component: 'Select',
      componentProps: {
        placeholder: '支持模糊搜索',
        filterable: true,
        remote: true,
        loading: false,
        remoteMethod: (no) => searchUser({ no }),
        options: [],
        on: {
          change: (val) => {
            searchParams.value.id = val
          }
        }
      }
    },
    form: { hidden: true },
    detail: { hidden: true },
    slots: {
      default: ({ row }) => {
        return (
          <div onClick={() => showSelectTableEl(row)} class="w-full h-full cursor-pointer">
            {'支持点击查看'}
          </div>
        )
      }
    }
  },
  {
    field: 'task_status',
    label: '物流状态',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    formatter: (cellValue) => {
      return cellValue.task_status_text
    }
  },
  {
    field: 'deliver_line_no',
    label: '运输路线编号',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'deliver_driver_name',
    label: '配送司机',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'deliver_car_no',
    label: '配送车辆',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'create_time',
    label: '运单创建时间',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      slots: {
        default: ({ row }) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => DetailsAction(row)}>
                详情
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delUserApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const showCollapse = ref(false)
let currentAction = shallowRef()
let currentRow = ref<Row | undefined>(undefined)
const action = (component: Component, row?: Row) => {
  currentAction.value = component
  currentRow.value = row
  if (showCollapse.value === false) showCollapse.value = true
}
// 详情
const DetailsAction = async (row) => {
  const res = await detailsApi({ id: row.id })
  action(comId['Details'], res.data.info)
}
const closeCollapse = () => {
  showCollapse.value = false
}

const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogFormVisible = ref(false)
const dialogFormVisibleData = ref({})
const showSelectTableEl = (val) => {
  dialogFormVisibleData.value = val
  dialogFormVisible.value = true
}
provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap>
    <Search
      @register="searchRegister"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton>
    </div>
    <el-collapse-transition>
      <component
        :is="currentAction"
        @close="closeCollapse"
        @get-list="getList"
        v-show="showCollapse"
      />
    </el-collapse-transition>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
    <el-dialog v-model="dialogFormVisible" title="关联订单号">
      <div style="max-height: 500px; overflow-y: auto">
        <tableData :currentRow="dialogFormVisibleData" />
      </div>
    </el-dialog>
  </ContentWrap>
</template>
